package com.zzzzzz.core.data.filestore;

import org.bson.types.ObjectId;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

public class MongodbFileStorage implements FileStorage {

	private Mongo mongo;
	
	private String fileDbName;
	
	public MongodbFileStorage(Mongo mongo, String fileDbName) {
		this.mongo = mongo;
		this.fileDbName = fileDbName;
	}

	public String absoluteUrl(String fileId) {
		return null;
	}

	public String storeFile(FileData fileData) {
		DB db = mongo.getDB(fileDbName);
		GridFS gridFS = new GridFS(db);
		GridFSInputFile gridFSInputFile = gridFS.createFile(fileData.getInputStream());
		gridFSInputFile.setFilename(fileData.getFileName());
		gridFSInputFile.setContentType(fileData.getContentType());
		gridFSInputFile.save();
		String fileId = gridFSInputFile.getId().toString();
		
		return fileId;
	}
	
	public String storeFile(SimpleFileData fileData) {
		DB db = mongo.getDB(fileDbName);
		GridFS gridFS = new GridFS(db);
		GridFSInputFile gridFSInputFile = gridFS.createFile(fileData.getInputStream());
		gridFSInputFile.setFilename(fileData.getFileName());
		gridFSInputFile.setContentType(fileData.getContentType());
		gridFSInputFile.save();
		String fileId = gridFSInputFile.getId().toString();
		
		return fileId;
	}

	public GridFSDBFile getFileById(String id) {
		DB db = mongo.getDB(fileDbName);
		GridFS gridFS = new GridFS(db);
		GridFSDBFile gridFSDBFile = gridFS.findOne(ObjectId.massageToObjectId(id));
		return gridFSDBFile;
	}
	
	public GridFSDBFile getFileByFileName(String fileName) {
		DB db = mongo.getDB(fileDbName);
		GridFS gridFS = new GridFS(db);
		GridFSDBFile gridFSDBFile = gridFS.findOne(ObjectId.massageToObjectId(fileName));
		return gridFSDBFile;
	}
	
	public void deleteFileById(String id) {
		DB db = mongo.getDB(fileDbName);
		GridFS gridFS = new GridFS(db);
		gridFS.remove(ObjectId.massageToObjectId(id));
	}
	
	public void deleteFileByFileName(String fileName) {
		DB db = mongo.getDB(fileDbName);
		GridFS gridFS = new GridFS(db);
		gridFS.remove(fileName);
	}
	
}